package globalValues

import (
	"math/rand"
	"strings"
	"time"
)

var tokensMap map[string]time.Time
var charSet = []byte{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}

func init() {
	tokensMap = make(map[string]time.Time)
}

// CreateToken 生成token
func CreateToken() string {
	cleanToken()
	rand.Seed(time.Now().Unix())
	var sb = strings.Builder{}
	for i := 0; i < 40; i++ {
		sb.WriteByte(charSet[rand.Intn(26)])
	}
	var token = sb.String()
	tokensMap[token] = time.Now().Add(time.Hour * 8)
	return token
}

// CheckToken 检查token
func CheckToken(token string) bool {
	cleanToken()
	_, ok := tokensMap[token]
	if !ok {
		return false
	}
	tokensMap[token] = time.Now().Add(time.Hour * 8)
	return true

}

//清除失效的token
func cleanToken() {
	for key, val := range tokensMap {
		if val.Before(time.Now()) {
			delete(tokensMap, key)
		}
	}
}
